package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.pojos.CommentRepayVo;
import com.heima.comment.service.CommentRepayService;
import com.heima.feign.user.IUserClient;
import com.heima.feign.wemedia.IWemediaClient;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.dtos.ScanCommentContentDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private IUserClient userClient;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询评论回复列表
     * @param dto
     * @return
     */
    public ResponseResult queryComment(CommentRepayDto dto) {
        //1.检查参数
        if(dto == null || dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.加载数据
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime")).limit(10);
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //3.数据封装返回
        //3.1 用户未登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.okResult(apCommentRepays);
        }
        //3.2 用户已登录
        //需要查询当前评论中哪些数据被点赞了
        List<String> idList = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentRepayId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        if(apCommentRepayLikes == null || apCommentRepayLikes.size() == 0 ){
            return ResponseResult.okResult(apCommentRepays);
        }
        List<CommentRepayVo> resultList = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            CommentRepayVo vo = new CommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay,vo);
            for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                if(apCommentRepay.getId().equals(apCommentRepayLike.getCommentRepayId())){
                    vo.setOperation((short)0);
                    break;
                }
            }
            resultList.add(vo);
        }
        return ResponseResult.okResult(resultList);
    }

    /**
     * 点赞评论
     * @param dto
     * @return
     */
    public ResponseResult likeComment(CommentRepayLikeDto dto) {
        //1.检查参数
        if(dto == null || dto.getCommentRepayId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        //3.点赞
        if(apCommentRepay != null && dto.getOperation() == 0){
            //更新评论点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes()+1);
            mongoTemplate.save(apCommentRepay);
            //保存评论点赞数据
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentRepayLike);
        }else {
            //更新评论点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes()-1);
            mongoTemplate.save(apCommentRepay);
            //删除评论点赞
            Query query = Query.query(Criteria.where("commentRepayId")
                    .is(apCommentRepay.getId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query,ApCommentRepayLike.class);
        }
        //4.取消点赞
        Map<String,Object> result = new HashMap<>();
        result.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(result);
    }

    /**
     * 保存评论回复
     * @param dto
     * @return
     */
    public ResponseResult saveComment(CommentRepaySaveDto dto) {
        //1.校验参数
        if (dto == null || dto.getCommentId() == null || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否登录
        if (AppThreadLocalUtil.getUser() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "请登录后再进行该操作！");
        }
        //3.评论内容不能超过140字
        if (dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_FAIL,"评论内容不能超过140字");
        }

        //4.垃圾检测
        ScanCommentContentDto scanCommentContentDto = new ScanCommentContentDto();
        scanCommentContentDto.setContent(dto.getContent());
        Boolean result = wemediaClient.commentScan(scanCommentContentDto);
        if (result){
            //5.更新评论的回复数量
            ResponseResult res = userClient.selectApUser(AppThreadLocalUtil.getUser());
            if (res.getCode().equals(200)){
                String apUserJson = JSON.toJSONString(res.getData());
                ApUser apUser = JSON.parseObject(apUserJson, ApUser.class);
                ApCommentRepay apCommentRepay =ApCommentRepay.builder()
                        .authorId(apUser.getId())
                        .authorName(apUser.getName())
                        .createdTime(new Date())
                        .commentId(dto.getCommentId())
                        .content(dto.getContent())
                        .likes(0)
                        .build();
                mongoTemplate.save(apCommentRepay);

                ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
                apComment.setReply(apComment.getReply() + 1);
                mongoTemplate.save(apComment);
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"获取用户信息失败");
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容违规！");
        }
    }
}
